import java.util.Arrays;



public class Heap {
    public int[] elem;
    public int usedSize;

    public static final int DEFAULT_SIZE=10;
    public Heap(){
        this.elem=new int[DEFAULT_SIZE];
    }
    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i]=array[i];
            usedSize++;
        }
    }

    public void createHeap(){
        for (int parent = (usedSize-1-1)/2; parent >0 ; parent--) {
                siftDown(parent,usedSize);
        }
    }
    public void siftDown(int parent,int len){
        //至少有左孩子
        int child = 2*parent+1;
        while (child<len){
            //如果child越界，就会报错，所以
            if (child+1<len&&elem[child]<elem[child+1]){
                child=child+1;
            }
            if(elem[child]>elem[parent]){
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }
    private void swap(int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }


    public void push(int val){
        //满了
        if(isFull()){
            elem=Arrays.copyOf(elem,elem.length*2);
        }
        siftUp(usedSize);

        usedSize++;
    }

    public boolean isFull(){
        return usedSize==elem.length;
    }
    public void siftUp(int child){
        int parent=(child-1)/2;
        while (child>0){
            if (elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }
    public int pop(){
        //判断是不是空
        if(isEmpty()){
            throw new Nornull("为空不能删除");
        }
        int oldVal=elem[0];
        swap(0,usedSize);
        usedSize--;
        siftDown(0,usedSize);
        return oldVal;
    }
    public boolean isEmpty(){
        return usedSize==0;
    }

}
